//
//  UserAccount.swift
//  weibo2
//
//  Created by xuwzh on 15/10/7.
//  Copyright © 2015年 xuwzh. All rights reserved.
//

import UIKit

import Alamofire

/*

在swift中，如果要打印类信息，需要遵守一个协议Printable
*/

class UserAccount: NSObject{
    
    let access_token : String	//用于调用access_token，接口获取授权后的access token。
    let expires_in : NSTimeInterval    // access_token的生命周期，单位是秒数。
    let expiresDate : NSDate //过期日期
    let uid : String	//当前授权用户的UID。
    
    
    ///用户的名称
    var name :String?
    ///用户头像地址（大图），180×180像素
    var avatar_large :String?
    
    init(dict: [String : AnyObject]){
        access_token=dict["access_token"] as! String
        expires_in=dict["expires_in"] as! NSTimeInterval
        expiresDate=NSDate(timeIntervalSinceNow: expires_in)
        uid=dict["uid"] as! String
        
    }
    
    ///定义保存用户信息路径
    static let accountPath=(NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!).stringByAppendingString("account.plist")
    
    ///  加载 token,,如果出错就回调
    class func loadAccessToken(params: [String: String],completion:(account: UserAccount?,error: AnyObject?) ->()) {
        Alamofire.request(.POST, "https://api.weibo.com/oauth2/access_token", parameters:params).responseJSON() {
            (_, _, json) in
            
            
            print("请求到的数据======\(json.value)")
            //字典转模型
            if((json.value) != nil){
                
                ///请求数据转换成对象成功，才能继续请求
                if let dict = json.value as? [String:AnyObject]{
                    //                if let dict=UserAccount.init(dict: json.value  as! [String : AnyObject]){
                    ///对象模型
                    let account=UserAccount.init(dict: dict)
                    
                    //请求用户信息
                    account.loadUserInfo(completion)
                    
                }else{
                    let error=NSError(domain: "HM.WeiBo", code: (-1), userInfo: ["error":"数据请求异常，请检查网络"])
                    completion(account: nil, error: error)
                    return
                    
                }
            }
            
            
        }
    }
    
    ///请求用户信息
    func loadUserInfo(completion:(account: UserAccount?,error : AnyObject?) ->()){
        
        let urlString="https://api.weibo.com/2/users/show.json"
        let parms=["access_token":access_token,"uid":uid]
        Alamofire.request(.GET, urlString, parameters: parms).responseJSON() { (_ , _ , json) -> Void in
            print(json.value)
            if((json.value) != nil ){
                
                if let dict = json.value as? [String:AnyObject]{
                    self.name=dict["name"] as? String
                    self.avatar_large=dict["avatar_large"] as? String
                    
                    ///键值归档保存数据
                    NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
                    print("保存路径" + UserAccount.accountPath)
                    
                    completion(account: self, error :json.value)
                }else{
                    let error=NSError(domain: "HM.WeiBo", code: (-1), userInfo: ["error":"数据请求异常，请检查网络"])
                    completion(account: nil, error: error)
                    return
                    
                }
            }
            
            
            
        }
        
    }
    
    class func loadUserAccount() ->UserAccount?{
        
        if let account=NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount{
            
            ///如果过期时间比当前时间大，降序的结果，就返回accouont
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
                
            }
        }
        return nil
    }
    
    
    ///此方法用来输出类是属性值，tostring方法类似
    override var description: String {
        
        let propties = [ "access_token","expires_in","uid","expiresDate","avatar_large","name"]
        let string =  dictionaryWithValuesForKeys(propties)
        print(string)
        return ""
    }
    
    ///归档器
    
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid , forKey: "uid")
        aCoder.encodeObject(avatar_large,forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    
    ///解档器
    required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        expiresDate = (aDecoder.decodeObjectForKey("expiresDate") as? NSDate)!
        uid = aDecoder.decodeObjectForKey("uid") as! String
        avatar_large=aDecoder.decodeObjectForKey("avatar_large") as?String
        name=aDecoder.decodeObjectForKey("name") as?String
        
    }
    
}







